from flask_wtf import FlaskForm
from wtforms import widgets, validators, ValidationError
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.fields import simple

from ..services.user_admin_svr import UserAdminSVR


def get_roles():
    return UserAdminSVR.get_all_roles()


def check_parent_id(form, field):
    if form.parent_role.data != None and form.parent_role.data._id == form.role_id.data:
        raise ValidationError(u'父节点不能选择自己！')


class RolesFM(FlaskForm):

    def __init__(self, *args, **kwargs):
        super(RolesFM, self).__init__(*args, **kwargs)

    role_id = simple.HiddenField();
    role_name = simple.StringField(
        label="角色名：",
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'class="col-sm-3 control-label form-control', 'placeholder': "请输入角色名"}

    )
    role_type = simple.StringField(
        label="角色类型：",
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'col-sm-3 form-control', 'placeholder': "请输入角色类型"}

    )

    parent_role = QuerySelectField(label="选择父节点：", validators=[check_parent_id, ], query_factory=get_roles,
                                   allow_blank=True)

    def update_role(self, role_md):
        role_md.name = self.role_name.data
        role_md.role_type = self.role_type.data
        role_md._id = self.role_id.data
        if self.parent_role.data != None:
            role_md.parent_id = self.parent_role.data._id
        return role_md

    def update_self(self, role_md):
        self.role_id.data = role_md.id
        self.role_name.data = role_md.name
        self.role_type.data = role_md.role_type
